package com.ericsson.eritask.dao.impl;

import java.io.IOException;
import java.io.InputStream;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.stereotype.Repository;

import com.ericsson.eritask.dao.ImageDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;

@Repository
public class ImageDaoImpl implements ImageDAO {

	@Autowired
	GridFsOperations gridOperations;

	@Override
	public String insertImage(InputStream image,String fileName) {

		
		  DBObject metaData = new BasicDBObject(); 
		  metaData.put("extra1", "anything 1"); 
		  metaData.put("extra2", "anything 2");
		  
//		  String arr[]=image.toString().split("/");
//		  System.out.println("arr is ::::::"+arr);
//		  String fileName = null;
//		  for(int i = 0; i<=arr.length-1;i++){
//			  fileName = arr[arr.length-1].toString();
//			  System.out.println("Image filename===="+fileName);
//		  }
		GridFSFile storedFile = null;
		try {
		System.out.println("filename in imagedaoimpl::::" +fileName);
			storedFile = gridOperations.store(image,fileName, metaData);
			String id = storedFile.getId().toString();
			System.out.println("Image id in imagedaoimpl is" + id);
		} finally {
			if (image != null) {
				try {
					image.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return storedFile.getId().toString();
	}

	@Override
	public InputStream getImgStreamById(String id) {

		GridFSDBFile recievedFile = gridOperations.findOne(new Query(Criteria.where("_id").is(new ObjectId(id))));
		System.out.println("=="+recievedFile);
		System.out.println(recievedFile.getId());
		System.out.println(recievedFile.getContentType());

		//save as another image
		//recievedFile.writeTo("C:/Users/Public/Pictures/Sample Pictures/Desert1111.jpg");


		return recievedFile.getInputStream();
	}
}